//
//  DownloadingViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/21.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let opButtonCellIdentifier = "DownloadingOpCell"
private let audioCellIdentifier = "AudioTableCell"

class DownloadingViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet weak var tableView: UITableView!
  
  // MARK: - Private vars
  
  
  
  // MARK: - Private methods
  
  private func prepareUI() {
    tableView.register(UINib(nibName: audioCellIdentifier, bundle: nil), forCellReuseIdentifier: audioCellIdentifier)
    tableView.contentInset = UIEdgeInsets.init(top: 20, left: 0, bottom: 40, right: 0)
    tableView.scrollIndicatorInsets = tableView.contentInset
  }
  
  private func addNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(downloadFinished(notifiation:)), name: .downloadFinished, object: nil)
//    NotificationCenter.default.addObserver(self, selector: #selector(downloadDidFailed(notifiation:)), name: .downloadFailded, object: nil)
  }
  
  @objc private func downloadFinished(notifiation: Notification) {
    if let object = notifiation.userInfo?[DownloadNotificationObject.key] as? DownloadNotificationObject {
      for (index, audio) in audios.enumerated() {
        if object.downloadModel.fileURL == audio.url {
          audios.remove(at: index)
          tableView.deleteRows(at: [IndexPath(row: index + 1, section: 0)], with: .automatic)
          if audios.count == 0 {
            navigationController?.popViewController(animated: true)
          }
          break
        }
      }
    }
  }
  
//  @objc private func downloadDidFailed(notifiation: Notification) {
//    if let object = notifiation.userInfo?[DownloadNotificationObject.key] as? DownloadNotificationObject {
//      for (index, audio) in audios.enumerated() {
//        if object.downloadModel.fileURL == audio.url {
//          audios.remove(at: index)
//          tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
//          break
//        }
//      }
//    }
//  }
  
  // MARK: - Public vars
  
  private var audios = [Audio]()
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    addNotifications()
    prepareUI()
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    audios = AudioDownloadManager.shared.getDownloadingAudios()
    tableView.reloadData()
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  deinit {
    NotificationCenter.default.removeObserver(self)
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  
}

// MARK: - UITableViewDataSource

extension DownloadingViewController: UITableViewDataSource {
  
  func numberOfSections(in tableView: UITableView) -> Int {
    return 1
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return audios.count + 1
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
      let cell = tableView.dequeueReusableCell(withIdentifier: opButtonCellIdentifier, for: indexPath) as! DownloadingOpCell
      cell.delegate = self
      return cell
    } else {
      let cell = tableView.dequeueReusableCell(withIdentifier: audioCellIdentifier, for: indexPath) as! AudioTableCell
      let audio = audios[indexPath.row - 1]
      cell.prepare(audio: audio)
      cell.selectionStyle = .none
      return cell
    }
  }
  
  func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return indexPath.row > 0
  }
  
  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
      let audio = audios[indexPath.row - 1]
      AudioDownloadManager.shared.remove(audio: audio)
      audios.remove(at: audios.index(of: audio)!)
      tableView.deleteRows(at: [indexPath], with: .automatic)
    }
  }
}

// MARK: - UITableViewDelegate

extension DownloadingViewController: UITableViewDelegate {
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == 0 {
      return 44
    } else {
      return 60
    }
  }
}

// MARK: - DownloadingOpCellDelegate

extension DownloadingViewController: DownloadingOpCellDelegate {
  func downloadAll() {
    AudioDownloadManager.shared.resumeQueue()
  }
  
  func pauseAllDownload() {
    AudioDownloadManager.shared.pauseQueue()
  }
  
  func removeAllDownload() {
    AudioDownloadManager.shared.getDownloadingAudios().forEach {
      AudioDownloadManager.shared.remove(audio: $0)
    }
    audios = AudioDownloadManager.shared.getDownloadingAudios()
    tableView.reloadSections(IndexSet(0...0), with: .fade)
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
      self.navigationController?.popViewController(animated: true)
    }
  }
}
